package edu.sdwu.liqing.qasystem.util;


import edu.sdwu.liqing.qasystem.entity.QaUser;
import edu.sdwu.liqing.qasystem.service.IQaUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Component
public class RequestUtil {

    @Autowired
    IQaUserService userService;

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public String getToken() {
        return getRequest().getHeader("qa-token");
    }

    public QaUser getCurrentUser() {
        String token = getToken();
        String username = JWTUtil.getUsername(token);
        if (StringUtils.isBlank(username)) {
            return null;
        }
        QaUser user = userService.getUserByUsername(username);
        if (Objects.isNull(user)) {
            return new QaUser();
        }
        return user;
    }

}
